package com.sunmouse.toollib.utils.load;

import android.os.Handler;
import android.os.Message;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sunmouse.toollib.constants.Load;
import com.sunmouse.toollib.utils.LogUtils;

public class LoadTask extends Thread {
    private long start;
    private long readSize;
    private URL url;
    private File output;
    private Handler mHandler;
    private Message msg;


    @Override
    public void run() {
        super.run();
        try {
            //long cp = 0;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setRequestProperty("Range", "bytes=" + start + "-" + (start
                    + readSize));
            int status = conn.getResponseCode();
            LogUtils.v("status=" + status);
            if (conn.getResponseCode() == 206) {//partial content
                BufferedInputStream bis = new BufferedInputStream(
                        conn.getInputStream());
                RandomAccessFile rafOut = new RandomAccessFile(output, "rw");
                // bis.mark((int) start);
                // bis.skip(start);
                rafOut.seek(start);
                int len = 0;
                byte[] b = new byte[LoadUtils.READ_SIZE];
                while ((len = bis.read(b)) != -1) {
                    rafOut.write(b, 0, len);
                    sendMsg(Load.LOADING,len,-1);
//                    LogUtils.v("loading...");
                }
                rafOut.close();
                bis.close();
                conn.disconnect();
                sendMsg(Load.THREAD_FINISH,-1,-1);
//                LogUtils.v(getName() + ":" + start + "----finish");
            }
        } catch (IOException e) {
            e.printStackTrace();
            sendMsg(Load.THREAD_FINISH,-1,-1);
        }

    }

    public LoadTask(long start, long end, URL url,
                    File output, Handler mHandler) {
        super();
        if (url == null) {
            throw new RuntimeException("Error url is invalid");
        }
        this.start = start;
        this.readSize = end;
        this.url = url;
        this.output = output;
        this.mHandler = mHandler;
    }

    /**
     * a task factory
     */
    public static LoadTask newTask(long start, long end, URL url,
                            File output, Handler mHandler) {
        return new LoadTask(start, end, url, output, mHandler);
    }


    /**
     * send msg
     * read
     */
    private void sendMsg(int status, int read, int position) {
        msg = Message.obtain();
        msg.what = status;
        msg.arg1 = read;
        msg.arg2 = position;
        mHandler.sendMessageDelayed(msg, 1000);
    }
}
